package cn.mai.action;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.mai.domain.Dialog;
import cn.mai.service.ChatService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Actions
@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("json-default")
public class ChatAction extends ActionSupport implements ModelDriven<Dialog> {

	private Dialog dialog = new Dialog();

	@Override
	public Dialog getModel() {
		return dialog;
	}

	@Autowired
	private ChatService chatService;

	@Action(value = "chat", results = { @Result(name = "success", type = "json") })
	public String chat() {
		String msg = chatService.findAnswer(dialog);
		Map<String, Object> result = new HashMap<String, Object>();
		if (msg == null) {
			result.put("flag", 1);
		} else {
			result.put("msg", msg);
		}
		ServletActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}

	@Action(value = "saveDialog", results = { @Result(name = "success", type = "json") })
	public String saveDialog() {
		// System.out.println(dialog);
		chatService.save(dialog);
		String msg = dialog.getAnswer();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("msg", msg);
		ServletActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}

}
